Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

147
Views
How to count number of occurrences in a very big text for each keyword (regEx) of an array [JS]

This problem is mostly related to an optimization.

Suppose I have a very big text (const text = "...") and an big array of keywords (const keywords = ["one", "good days", "ar.i.t", ...]). You can notice that this keywords might be a single word, multiple words or any RegEx expresion. I need to count how many times each keyword (expression) occurs in the text.

My approach would be as follows:

const text = "..."
const keywords = [...]

keywords.forEach(keyword => {
    const re = new RegExp(keyword, "gi");
    const count = (text.match(re) || []).length;
})

The problem with this approach is that it is very slow (if text is big enough and array as well). I have to iterate through the entire text again and again until every keyword is checked. Could someone suggest an idea of an algorithm that would go through text only once and count occurence for every keyword, or any idea that could solve the problem faster.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

This might help slightly:

const str = 'this is a piece of text this is text this is text';

const countOcc = () => {
  const regex = /this/g, result, indices = [];
  while ((result = regex.exec(str))) {
    indices.push(result.index);
  }
  return indices.length
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!